<?php

/**
 * @author
 * @copyright 2014
 */
class Klgb extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model();
        $this->load->model(array('excel_model','login_model','department_model')); //$this->lang->load('title');
    }
    function _remap($method, $params = array()) {
        if (method_exists($this, $method)) {
            return call_user_func_array(array($this, $method), $params);
        }
        $this->_view();
    }
    function _view() {
		
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			redirect(base_url().'authorize');
		}
		
		$data = new stdClass();
        $this->load->helper('form');
        $data->page = 0;
        $title = "Trung tâm"; 
		$data->groups = $login['groups'];
		$controller = $this->uri->segment(1);
		$data->cotrol = $controller;
		$right = $this->login_model->permission($controller); 
		
		if(!isset($right['view'])){
			redirect(base_url().'home');
		}
		$data->rights = $right;
		if(isset($_GET['t'])){
			$data->loai = $_GET['t'];
		}
		else{
			$data->loai = "";
		}
		$arr_lkl = $this->model->loaiketluan();
		$data->loaiketluans = form_dropdown('loaiklss', $arr_lkl,'', 'id="loaikls" style="width:158px; height:26px;" class=""');
		$chutris = $this->model->listChutri();
		$data->chutris = form_dropdown('chutriss', $chutris,'', 'id="chutris" style="width:258px; height:26px;" class=""');
		
		$nvchuyenquans = $this->model->combo_chuyenquan($login);
		$data->nvchuyenquans = form_dropdown('nvchuyenquanss', $nvchuyenquans,'', 'id="nvchuyenquans" style="width:258px; height:26px;" class=""');
		
		$phongbans = $this->model->combo_phongban($login);
		$data->phongbans = form_dropdown('phongbanss', $phongbans,'', 'id="phongbans" style="width:158px; height:26px;" class=""'); 
		
		$pheduyet = $this->model->loaipheduyet();
		$data->pheduyets = form_dropdown('pheduyet', $pheduyet,'', 'id="pheduyet" style="width:158px; height:26px;" class=""');
		
		 $name_controller = $this->router->fetch_class();		 
		 $tab_list = $this->model
							 ->table('tabs')
							 ->where('module',$name_controller)
							 ->where('isdelete',0)
						 	 ->order_by('ordering')
							 ->find_all();
		foreach($tab_list as $tab) {
			$number = $this->model->tab_load_sql($tab->sql);
			$tab->number=$number;
		}
		$data->tab_list = $tab_list;
		//print_r($tab_list); exit();		
        $content = $this->load->view('view', $data, true);
		$this->pub->write('title',$title,true);
		$this->pub->write('content',$content,true);
        $this->pub->render();
    }
		function test(){
		$login = $this->pub->GetSession('login');
		print_r($login['id']);
	}
	function getList(){
		 $data = new stdClass();
		 $result = new stdClass();
		 $page=$this->input->post('page');
         $counts= $this->input->post('count');

		 $login = $this->pub->GetSession('login');
		 $groups = $login['groups'];
		 $page=$this->input->post('page');
         $rows = (empty($counts))?$this->pub->config['numrows']:$counts;

		$search = json_decode($this->input->post('search'),true);
		$controller = $this->uri->segment(1);
		$right = $this->login_model->permission($controller); 
		$data->rights = $right;
		if(isset($_GET['t'])){
			$loai = $_GET['t'];
		}
		 else{
			$loai = "";
		 }
		 $sql = $this->model->getList($search,$loai,$login);
		 //echo $sql; exit();
		 $sql.= " order by kl.id DESC";
		 $count  = $this->model->getTotal($search,$loai,$login);
		 if($rows!='Tất cả')
		 {			
			 if($page == 0){
				$sql = $sql." limit $rows ";
			 }
			 else{
				$sql = $sql." limit ".$page.",".$rows."";
			 }
		 } else {
				 $rows = $count; 
		 }
		 
		 $query = $this->model->query($sql)->execute();
		 //echo $sql;
		 $loaipheduyet = $this->model->loaipheduyet();		 
		 $data->loaipheduyet = $loaipheduyet;
		 
		 $data->lists = $this->model->getIDPhongbanList($login);
		 $page_view='&nbsp;';
		 if($count>0){
		 //echo "phantrang($count,$rows,5,'klgb/',$page)";
			$page_view=$this->pub->phantrang($count,$rows,5,'klgb/',$page);
		 }
         if(empty($page_view)) $page_view='&nbsp;';
         $result->paging = $page_view;
		
         $result->cPage = $page;
		 $data->datas = $query;
		 $data->groups = $groups;
		 $data->count = $count;
		 
		 //echo "<pre>"; print_r($result); exit();
		 
         $result->content = $this->load->view('list',$data,true);
         $result->action = $this->pub->action;
		 //echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
		 //print_r($result);
		 echo json_encode($result);
	}
	function insert(){
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			redirect(base_url().'authorize');
		}
		 $this->load->helper('form');
		 $data = new stdClass();
		 $arr_lkl = $this->model->loaiketluan();
		 $data->loaiketluans = form_dropdown('data[loaikl]', $arr_lkl,'', 'id="loaikls" style="width:158px; height:26px;" class=""');
		 
		 $chutris = $this->model->listChutri();
		 $data->chutris = form_dropdown('data[chutri]', $chutris,'', 'id="chutris" style="width:158px; height:26px;" class=""');
		 
		 $data->nguoiketluans = form_dropdown('data[nguoiketluan]', $chutris,'', 'id="nguoiketluan" style="width:158px; height:26px;" class=""');
		 
		 $nvchuyenquans = $this->model->combo_chuyenquan($login);
		 $data->nvchuyenquans = form_dropdown('data[nvchuyenquan]', $nvchuyenquans,'', 'id="nvchuyenquans" style="width:158px; height:26px;" class=""');
		 
		 $arr_donvi_soap = $this->model->arr_donvi_soap($login);
		 $phongbans = array();
		 $trungtams = array();
		 for($i=0; $i<count($arr_donvi_soap); $i++) {
			 if($arr_donvi_soap[$i]['loai']==1) {
			 	$phongbans[$arr_donvi_soap[$i]['id']] = $arr_donvi_soap[$i]['ten'];
			 } elseif($arr_donvi_soap[$i]['loai']==2) {
				 $trungtams[$arr_donvi_soap[$i]['id']] = $arr_donvi_soap[$i]['ten'];
			 }
		 }		
		 //echo "<pre>"; print_r($arr_donvi_soap); exit;
		 $data->phongbans = form_dropdown('datas[phongban][]', $phongbans,'', 'id="phongbans" style="width:158px; height:26px;" class=""');
		 $data->trungtams = form_dropdown('datas[trungtam][]', $trungtams,'', 'id="trungtams" style="width:158px; height:26px;" class=""');
		
		 $loaigiaoban = $this->model->loaigiaoban();
		 $data->loaigiaobans = form_dropdown('data[loaigiaoban]', $loaigiaoban,'', 'id="loaigiaoban" style="width:158px; height:26px;" class=""');
		 
		 $data->phongbans2 = form_dropdown("datas[phongbans2][]", $phongbans,"", "id='phongbans2' style='width:158px; height:26px;' class='combo phongbans2'");
		 
		 $data->phongbans2s = $phongbans;
		 $data->titles = "Thêm mới kết luận";
		 $content = $this->load->view('form', $data, true);
		 $this->pub->write('content',$content,true);
         $this->pub->render();	
	}
	function edit($ids){
		 $login = $this->pub->GetSession('login');
		 if(empty($login['taikhoan'])){
			redirect(base_url().'authorize');
		 }
		 $this->load->helper('form');
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
		 $query = $this->model->where('id',$ids)->find();
		 
		 $data->ngaygiaoban = date('d-m-Y',strtotime($query->ngaygiaoban));
		 $data->ngayhoanthanh = date('d-m-Y',strtotime($query->ngayhoanthanh));
		 
		 $arr_lkl = $this->model->loaiketluan();
		 $data->loaiketluans = form_dropdown('data[loaikl]', $arr_lkl,$query->loaikl, 'id="loaikls" style="width:158px; height:26px;" class=""');
		 
		 $chutris = $this->model->listChutri();
		 $data->chutris = form_dropdown('data[]', $chutris,$query->chutri, 'id="chutris" style="width:158px; height:26px;" class=""');
		 
		 $data->nguoiketluans = form_dropdown('data[nguoiketluan]', $chutris,$query->nguoiketluan, 'id="nguoiketluan" style="width:158px; height:26px;" class=""');
		 
		 //$nvchuyenquans = $this->model->listChuyenquan();
		 $nvchuyenquans = $this->model->combo_chuyenquan($login);
		 $data->nvchuyenquans = form_dropdown('data[nvchuyenquan]', $nvchuyenquans,$query->nvchuyenquan, 'id="nvchuyenquans" style="width:158px; height:26px;" class=""');
		 
		 $arr_donvi_soap = $this->model->arr_donvi_soap($login);
		 $phongbans = array();
		 $trungtams = array();
		 $donvis = array();
		 for($i=0; $i<count($arr_donvi_soap); $i++) {
			 if($arr_donvi_soap[$i]['loai']==1) {
			 	$phongbans[$arr_donvi_soap[$i]['id']] = $arr_donvi_soap[$i]['ten'];
			 } elseif($arr_donvi_soap[$i]['loai']==2) {
				 $trungtams[$arr_donvi_soap[$i]['id']] = $arr_donvi_soap[$i]['ten'];
			 }
			 $donvis[$arr_donvi_soap[$i]['id']] = $arr_donvi_soap[$i]['ten'];
		 }		
		 //echo "<pre>"; print_r($arr_donvi_soap); exit;
		 $data->phongbans = form_dropdown('datas[phongban][]', $phongbans,'', 'id="phongbans" style="width:158px; height:26px;" class=""');
		 $data->trungtams = form_dropdown('datas[trungtam][]', $trungtams,'', 'id="trungtams" style="width:158px; height:26px;" class=""');
	
		 $data->phongbans2 = form_dropdown('datas[phongbans2][]', $donvis,'', 'id="phongbans2" style="width:158px; height:26px;" class=""'); 
		
		 $loaigiaoban = $this->model->loaigiaoban();
		 $data->loaigiaobans = form_dropdown('data[loaigiaoban]', $loaigiaoban,'', 'id="loaigiaoban" style="width:158px; height:26px;" class=""');
		 $listPhongban = $this->model->getIDPhongban($ids);	
		 $str = "";
		 foreach($listPhongban as $id=>$nd){
			$str.= ",".$id;
		 }
		 $data->str = $str;
		 
		 $listSub2 = $this->model->getIDPhongbanSub($ids);
		 $str2 = "";
		 //echo "<pre>"; print_r($phongbans); exit();
		 foreach($listSub2 as $sub){
			$str2.= ",".$sub->id;
		 }
		 		 
         if(!empty($data->nvchuyenquan)) {
            $data->nvchuyenquan = substr($data->nvchuyenquan,1);
            $data->nvchuyenquan = substr($data->nvchuyenquan,0,-1);
         }         
		 
         $data->phongbans2s = $phongbans;
		 $data->str2 = $str2;
		 $data->listSub2 = $listSub2;
		 $data->datas = $query;
		 $data->ids = $ids;
		 $data->titles = "Sửa kết luận";
		 $data->listSub2 = $listSub2;
		 //echo "<pre>"; print_r($data); exit();
		 $content = $this->load->view('edit', $data, true);
		 $this->pub->write('content',$content,true);
         $this->pub->render();
	}
	function import(){
		$data = new stdClass();
		$data->titles = "";
		if(isset($_GET['tc'])){
			$data->titles = "Import thành công.";
		}
		$filename ='mau_import.xls';       
        $download_path = str_replace("index.php","",$_SERVER['SCRIPT_NAME']).''.$filename;
		$data->fileimport = $download_path;
		$content = $this->load->view('import', $data, true);
		$this->pub->write('content',$content,true);
        $this->pub->render();
	}
	
	 function readexcel1(){
        if (!empty($_FILES)) {
            $result['status'] = "no";
            $path = str_replace('\\','/',FCPATH).'/backup/';
            $filename = $_FILES['myfile']['name'];
            if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $path.$filename))
                $result = array("status"=>"yes","file"=>$path.$filename);
            echo json_encode($result);
        }
        else show_404();
    }
	
	function readexcel(){
		
		if (!empty($_FILES)) {           
            $path = str_replace('\\','/',FCPATH).'/backup/';
            $filename = $_FILES['myfile']['name'];
            if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $path.$filename)) {
				include(APPPATH.'libraries/excel2013/PHPExcel/IOFactory'.EXT);
				$inputFileType = PHPExcel_IOFactory::identify($path.$filename);
				$objReader = PHPExcel_IOFactory::createReader($inputFileType);
				$objReader->setReadDataOnly(true);
				$objPHPExcel = $objReader->load($path.$filename);
				$objPHPExcel->setActiveSheetIndex(0);
				$objWorksheet = $objPHPExcel->getActiveSheet();
				$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
				$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
				$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
				$login = $this->pub->GetSession('login');
			
				$list_nv = $this->model->list_nhanvien_manv();
				//OPTION 1   
				$sql_insert = 'INSERT INTO `klgb` (
										`sovanban` ,				
										`nvchuyenquan` ,
										`machuyenquan` ,
										`tenchuyenquan` ,
										`ghichu` ,
										`nguoitao` ,
										`ngaytao`
									)
									VALUES ';
									
				$i = 0;
				for ($row = 4; $row <= $highestRow; ++$row){
				
					$ma_cong_van = trim($objWorksheet->getCellByColumnAndRow(1, $row)->getValue());
					$ma_chuyen_quan =  strtolower(trim($objWorksheet->getCellByColumnAndRow(3, $row)->getValue()));
					$id_chuyen_quan =  isset($list_nv[$ma_chuyen_quan]['id'])?$list_nv[$ma_chuyen_quan]['id']:0;
					$tenchuyenquan =  isset($list_nv[$ma_chuyen_quan]['tennhanvien'])?$list_nv[$ma_chuyen_quan]['tennhanvien']:"";
					$ghi_chu = trim($objWorksheet->getCellByColumnAndRow(4, $row)->getValue());
					
					$sql_insert.= "(";
					$sql_insert.= "'".$ma_cong_van."',";
					$sql_insert.= "',".$id_chuyen_quan.",',";
					$sql_insert.= "',".$ma_chuyen_quan.",',";
					$sql_insert.= "',".$tenchuyenquan.",',";
					$sql_insert.= "'".$ghi_chu."',";
					$sql_insert.= "'".$login['taikhoan']."','".gmdate("Y-m-d H:i:s",time()+7*3600)."'),\n";
				}				
				$sql_insert = substr($sql_insert,0,-2).";";
				$this->model->table('klgb')->query($sql_insert)->execute();
				redirect(base_url().'klgb/import?tc=1');
			} 			
		}
		redirect(base_url().'klgb/import?tc=0');
	}
	function save(){
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			echo 0; exit;
		}
		$str = $this->input->post('obj');
		$phongban = $this->input->post('phongban');
		$trungtam = $this->input->post('trungtam');
		$noidung = $this->input->post('noidung');
		$ghichu = $this->input->post('ghichu');
		$id = $this->input->post('id');		
		$searchs = $this->input->post('searchs');
		$donvi = "";
		if(!empty($phongban))
			if(!empty($trungtam))
				$donvi = $phongban.",".$trungtam;
			else
				$donvi = $phongban;
		else
			$donvi = $trungtam;
			
		//echo "<pre>"; print_r($phongban); print_r($trungtam); exit();
		
		$regex = '/( [\x00-\x7F] | [\xC0-\xDF][\x80-\xBF] | [\xE0-\xEF][\x80-\xBF]{2} | [\xF0-\xF7][\x80-\xBF]{3} ) | ./x';
		$searchs = preg_replace($regex, '$1', $searchs);
		$searchs  =preg_replace('/.+?({.+}).+/','$1',$searchs); 
		$searchs = str_replace("\\t","",$searchs);		
		$searchs = str_replace("\\\\\\","",$searchs);
		$searchs = str_replace("\\","\\\\",$searchs);
		//$searchs = str_replace("\\","",$searchs);		
		
		$str = preg_replace($regex, '$1', $str);
		$str = preg_replace('/.+?({.+}).+/','$1',$str); 
		$str = str_replace("\\t","",$str);
		$str = str_replace("\\\\\\","",$str);
		$str = str_replace("\\","\\\\",$str);
	
		//print_r($searchs); exit();
		$objAdd = json_decode($searchs);
		//print_r($searchs); exit();
		if($str !='{}'){
			$json = json_decode($str);
			//print_r($json);exit();
			$data = array();                
			foreach($json as $clm=>$val){
				if($clm == 'ngaygiaoban' || $clm == 'ngayhoanthanh'){
					$val = date('Y-m-d',strtotime($val));
				}                
				$data[$clm] = $val;
			}
			$data['noidung'] = $noidung;
			$data['ghichu'] = $ghichu;
			$result = $this->model->saves($data,$donvi,$id,$objAdd);
			echo $result;
		}
		else{
			echo 0;
		}
	}
	function save2(){
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			echo 0; exit;
		}
		$id = $this->input->post('id');
		$themmoidung = $this->input->post('themmoidung');
		$phongban = $this->input->post('phongban');
		$this->model->saveDept2($id,$phongban,$themmoidung);
		echo 1;
	}
	function delete(){
		$last = $this->uri->total_segments();
		$record_num = $this->uri->segment($last);
		$id= $this->input->post('id');
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			//redirect(base_url().'authorize');
		}
		$result = $this->model->deletes($record_num);
		redirect(base_url().'klgb?status='.$result);
	}
	function loadSearch(){
		
		$key = $this->input->post('key');
		$cartype = $this->model->where('isdelete',0)
							   ->select('typename')	
							   ->like('typename',$key) 
							   ->limit(10)
							   ->find_all();
		$str = "";
		foreach($cartype as $item){
			$str.= ','.($item->typename).'';
		}
		$str = substr($str,1);
		echo $str; 
	}
	function setDuyet(){
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			echo 0; exit;
		}
		$id = $this->input->post('id');
		$check = $this->input->post('check');
		$this->model->where('id',$id)->update(array('tpduyet'=>$check));	
		echo 1;
	}
	function setPheDuyet(){
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			echo 0; exit;
		}
		$id = $this->input->post('id');
		$pd = $this->input->post('pd');
		$this->model->where('id',$id)->update(array('pheduyet'=>$pd));	
		echo 1;
	}
	
	function chamdiemdc(){
		 $this->load->helper('form');
		 $data = new stdClass();
		 $id =  $this->input->post('id');
		 
		 //$ketluancon = $this->model->listKetluancon($id);
		 $ketluancon = $this->model->listKetluanconSoap($id);
		 $arr = array();
		 $arr[0] = "Chọn phòng ban";
		 foreach($ketluancon as $item){
			 $arr[$item->idphongban] = $item->phongban;
		 }
		 $data->phongbans = form_dropdown('idphongban',$arr,'', 'id="idphongban" style="width:257px; height:26px;" class="combo"'); 
		 $data->id = $id;
		 echo $this->load->view('chamdiemdc', $data, true);	
	}
	
	function luuchamdiemdc(){
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			echo 0; exit;
		}
		$data = array();
		
		$id =  $this->input->post('id');
		 
		$diem =  $this->input->post('diem');
		$ghichu =  $this->input->post('ghichu');
		$idphongban =  $this->input->post('idphongban');
		
		#region Chấm điểm vào kl con
		$idketluancon = $this->model->idketluancon($id,$idphongban);
		if(!empty($idketluancon)){
			$data['diemdieuchinh'] = $diem;
			$query = $this->model->table('klphongban')->save($idketluancon,$data);
		}
		#end
		$arr_kq = array();
		//$objDep = $this->department_model->loadDepartment($idphongban);
		$objDep = $this->department_model->loadDepartmentSoap($idphongban);
		$arr_kq['idklgb'] = $id;
		$arr_kq['diem'] = $diem;
		$arr_kq['ghichu'] = $ghichu;
		$arr_kq['loai'] = 1;
		$arr_kq['idphongban'] = $idphongban;
		$arr_kq['madonvi'] = isset($objDep->usercode)?$objDep->usercode:"";
		$arr_kq['tendonvi'] = isset($objDep->names)?$objDep->names:"";
		$arr_kq['datecreate'] =  gmdate("Y-m-d H:s:i", time() + 7 * 3600);
		$arr_kq['usercreate'] = $login['taikhoan']; 
		$this->model->table('chamdiem')->save('',$arr_kq);
		
		$arr_cd = $this->model->table("klphongban")->select("diemdieuchinh")->where("idkl", $id)->find_all();
		$td=0;
		foreach($arr_cd as $item) {
			if(isset($item->diemdieuchinh))
				$td+=$item->diemdieuchinh;
		}
		$this->model->table('klgb')->where('id',$id)->update(array('chamdiemdc'=>$td));	
		
		echo 1;
		
	}
		
	function lichsuchamdiemqh_old(){
		 $login = $this->pub->GetSession('login');
		 $donvi = $login['donvi'];
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
		 $sql = "
			SELECT cd.*, d.`names` phongban
			FROM `chamdiem` cd
			left join department d on d.iduser = cd.idphongban
			WHERE cd.`idklgb` =  '2'
			AND cd.`loai` =  1
		 ";
		 		 
		 if($login['groups'] == 4 || $login['groups'] == 5){
			 $sql.= " and cd.idphongban = '$donvi'";
		 }	
		 $sql.= " ORDER BY cd.`datecreate` DESC";
		 $query = $this->model->query($sql)->execute();
		 $data->datas = $query;
		 echo $this->load->view('lichsuchamdiemqh', $data, true);	
	}
	
	function lichsuchamdiemqh(){
		 $login = $this->pub->GetSession('login');
		 $donvi = $login['donvi'];
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
		 $sql = "
			SELECT *, tendonvi as phongban
			FROM `chamdiem`
			WHERE `idklgb` =  '$id '
			AND `loai` =  1
		 ";
		 		 
		 if($login['groups'] == 4 || $login['groups'] == 5){
			 $sql.= " and idphongban = '$donvi'";
		 }
		 $sql.= " ORDER BY `datecreate` DESC";
		 $query = $this->model->query($sql)->execute();
		 $data->datas = $query;
		 echo $this->load->view('lichsuchamdiemqh', $data, true);	
	}
	
	function lichsuchamdiem(){
		 $this->load->helper('form');
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
		 $query = $this->model->table('chamdiem')
							  ->where('idklgb',$id)
							  ->where('loai',0)
							  ->order_by('datecreate','DESC')
							  ->find_all();			  
		 $data->datas = $query;
		 echo $this->load->view('lichsuchamdiemqh', $data, true);	
	}
	function traKetquaDetail(){
		 $this->load->helper('form');
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
		 $login = $this->pub->GetSession('login');
		 $donvi = $login['donvi'];
		 $sql = "SELECT kq.*, kl.noidung as noidungcon, kq.`tendonvi` as phongban
				FROM traketqua kq
				left join klphongban kl on kq.idklcon = kl.id			
				where kq.idklgb = '$id'
				";
		 
		 if($login['groups'] == 4 || $login['groups'] == 5){
			  $sql.= " and kq.deptid = '$donvi'";
		 }	
		 $query = $this->model->query($sql)->execute();		
		 
		 $data->traketquas = $query;
		 echo $this->load->view('traKetquaDetail', $data, true);	
	}
	function ycpkhDetail(){
		 $this->load->helper('form');
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
		 $query = $this->model->table('ycpkh')
							  ->where('idklgb',$id)
							  ->order_by('datecreate','DESC')
							  ->find_all();			  
		 $data->traketquas = $query;
		 echo $this->load->view('ycpkhDetail', $data, true);	
	}
	function ycpkh(){
		 $this->load->helper('form');
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
		 $query = $this->model->select('yeucauphongkh')->where('id',$id)->find();
		 $data->id = $id;
		 $data->yeucauphongkh = $query->yeucauphongkh;
		 echo $this->load->view('ycpkh', $data, true);	
	}
	function luuycpkh(){
		 $login = $this->pub->GetSession('login');
		 if(empty($login['taikhoan'])){
				//redirect(base_url().'authorize');
		 }
		 $data = array();
		 $arr_kq = array();
		 $id =  $this->input->post('id');
		 
		 $yeucauphongkh =  $this->input->post('yeucauphongkh');
		 $login = $this->pub->GetSession('login');

		$data['yeucauphongkh'] = $yeucauphongkh;
		$arr_kq['idklgb'] = $id;
		$arr_kq['noidung'] = $yeucauphongkh;
		$arr_kq['datecreate'] =  gmdate("Y-m-d H:s:i", time() + 7 * 3600);
		$arr_kq['usercreate'] = $login['taikhoan']; 

		$this->model->table('ycpkh')->save('',$arr_kq);
		$query = $this->model->table('klgb')->save($id,$data);
		echo 1;
		//redirect(base_url().'klgb'.url_suffix());
	}
	function yctp(){
		 $this->load->helper('form');
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
		 $query = $this->model->select('yctp')->where('id',$id)->find();
		 $data->id = $id;
		 $data->yctp = $query->yctp;
		 echo $this->load->view('yctp', $data, true);	
	}
	function luuyctp(){
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			echo 0; exit;
		}
		$data = array();
		$arr_kq = array();
		$id =  $this->input->post('id');
		 
		$yctp =  $this->input->post('yctp');
		$login = $this->pub->GetSession('login');

		$data['yctp'] = $yctp;
		$arr_kq['idklgb'] = $id;
		$arr_kq['noidung'] = $yctp;
		$arr_kq['datecreate'] =  gmdate("Y-m-d H:s:i", time() + 7 * 3600);
		$arr_kq['usercreate'] = $login['taikhoan']; 

		$this->model->table('yctp')->save('',$arr_kq);
		$query = $this->model->table('klgb')->save($id,$data);
		echo 1;
	}
	function yctpDetail(){
		 $this->load->helper('form');
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
		 $query = $this->model->table('yctp')
							  ->where('idklgb',$id)
							  ->order_by('datecreate','DESC')
							  ->find_all();			  
		 $data->traketquas = $query;
		 echo $this->load->view('yctpDetail', $data, true);	
	}
	function traKetqua(){
		 $this->load->helper('form');
		 $data = new stdClass();
		 $id =  $this->input->post('id');	
	//	 $query = $this->model->select('traketqua')->where('id',$id)->find();
		 $kqth = "";
			$arkq = $this->model->table("traketqua")->select("tendonvi, madonvi, noidung,datecreate,usercreate")
								->where("idklgb",$id)->order_by('datecreate', 'asc')->limit(1)->find_all();
			//echo "<pre>"; print_r($arrklpb); exit();
			$vt=1;
			foreach($arkq as $kq) {				
				$kqth.= $vt."/ ".$kq->datecreate." _ ".$kq->usercreate.": ".$kq->noidung."<br>";
				$vt++;
			}
		 $data->id = $id;
		 $data->traketqua = $kqth;
		 echo $this->load->view('traketqua', $data, true);	
	}
	function luuTraKetqua(){
		$login = $this->pub->GetSession('login');
		if(empty($login['taikhoan'])){
			echo 0; exit;
		}
        $data = array();
        $arr_kq = array();
        $id =  $this->input->post('id'); //ID Ket luan con
        
        $idketluancon = $this->model->idketluancon($id,$login['donvi']);
        
        $traketqua =  $this->input->post('traketqua');
        $this->load->library('upload');
        
        if (!empty($_FILES['userfile']['name'])){
        $folder = 'traketqua'; 
        $this->upload->initialize($this->set_upload_options($folder));
        $image_data = $this->upload->do_upload('userfile',$id); //Ten hinh
        $arr_kq['fileupload'] = $image_data; 
        }
		$data['traketqua'] = $traketqua;
		
		//$objDep = $this->department_model->loadDepartment($login['donvi']);
        //echo "<pre>"; print_r($login); exit();
        
		$objDep = $this->department_model->loadDepartmentSoap($login['donvi']);
		$arr_kq['idklgb'] = $id;
		$arr_kq['idklcon'] = $idketluancon;
		$arr_kq['noidung'] = $traketqua;
		$arr_kq['deptid'] = $login['donvi'];
		$arr_kq['madonvi'] = isset($objDep->usercode)?$objDep->usercode:"";
		$arr_kq['tendonvi'] = isset($objDep->names)?$objDep->names:"";
		$arr_kq['datecreate'] =  gmdate("Y-m-d H:s:i", time() + 7 * 3600);
		$arr_kq['usercreate'] = $login['taikhoan']; 
		$this->model->table('traketqua')->save('',$arr_kq);
		$query = $this->model->table('klgb')->save($id,$data);
		
		$klcha=$this->model->table('klphongban')->select('count(id)')->where('idkl',$id)->find();
	//	if($klcha>=2) echo 1; else echo 0;exit;
		$this->model->table('klphongban')->where('id',$idketluancon)->update(array('traketqua'=>$traketqua));
		$this->model->table('klgb')->where('id',$id)->update(array('traketqua'=>$traketqua));
		
		redirect(base_url().'klgb.html');
	}
	
	public function set_upload_options($folder) {
        $config = array();
        //$config['allowed_types'] = 'jpg|jpeg|gif|png|swf';
		$config['allowed_types'] = '*';
        $config['upload_path'] = './files/'.$folder.'/';
        $config['encrypt_nam'] = 'TRUE';
        $config['remove_spaces'] = TRUE;
        //$config['max_size'] = 10024;
        return $config;
    }
	
	function excel(){
		include(APPPATH . 'libraries/excel2013/PHPExcel/IOFactory' . EXT);
        $fileName = APPPATH . 'Template/ketluangiaoban.xls';
        $versionExcel = 'Excel5';
        $inputFileType = PHPExcel_IOFactory::identify($fileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($fileName);
        $sheetIndex = $objPHPExcel->setActiveSheetIndex(0);
        $sheetIndex->setTitle('Report');
        $sheetIndex->getDefaultStyle()->getFont()
                ->setName('Arial')
                ->setSize(12);
		
		$i= 4;
		$search = $_GET['search'];
		$search = json_decode($search,true);
		
		$login = $this->pub->GetSession('login');
		$sql = $this->model->getList($search,"",$login);
		$sql.= " order by kl.id DESC";
		$query = $this->model->query($sql)->execute();
		$ngay_hien_tai = strtotime(gmdate('Y-m-d',time()+7*3600));			
		$ngay_canh_bao = 3*86400;
		
		$list_nhanvien = array();//$this->model->list_nhanvien();
		
		foreach($query as $item){
			$id = $item->id;
			$codes = str_pad($id, 6, "0", STR_PAD_LEFT);
			
			if($item->ngaygiaoban != '0000-00-00'){
				$ngaygiaoban = date('d-m-Y',strtotime($item->ngaygiaoban));	
			}
			else{
				$ngaygiaoban = "";	
			}
			
			$tinh_trang = "";
			$mau="FFFFFF";
			if($item->ngayhoanthanh != '0000-00-00'){
				$ngayhoanthanh = date('d-m-Y',strtotime($item->ngayhoanthanh));	
				// Tinh toan tinh trang 
				$ngay_hoan_thanh = strtotime($item->ngayhoanthanh);
				$hieu_ngay = $ngay_hoan_thanh-$ngay_hien_tai;
				if($hieu_ngay < 0)//do
				{
					$tinh_trang = "quá hạn";
					$mau = "ff432a;'";				
				}
				elseif($hieu_ngay < $ngay_canh_bao)//vang
				{
					$tinh_trang = "trong hạn";
					$mau = "FFFF00;'";
				}
				else//xanh
				{
					$tinh_trang = "bình thường";
					$mau = "1e82fd;'";
				}	
			}
			else{
				$ngayhoanthanh = "";	
			}
			
			
			$noidung = strip_tags($item->noidung);
			$noidung = html_entity_decode($noidung,ENT_QUOTES,"UTF-8");
			$noidung = str_replace("&nbsp;","",$noidung)."\n";
			
			$pbth = "";
			$str_code = "";
			$arrklpb = $this->model->table("klphongban")->select("tendonvi, madonvi, noidung,ngayhoanthanh")->where("idkl",$item->id)->where('types', 1)->order_by('ngayhoanthanh','asc')->find_all();
			//echo "<pre>"; print_r($arrklpb); exit();
			$vt=1;
			foreach($arrklpb as $klpb) {
				$pbth.= "- ".$klpb->tendonvi.",\n";
			//	$str_code.= "\n".$vt."/ ".$codes.": ".$klpb->madonvi."-".$klpb->noidung."\n";
				$str_code.= "\n".$vt."/ ".$klpb->tendonvi.": ".$klpb->noidung."\n";
				$vt++;
			}
			
			/* $kqth = "";
			$arkq = $this->model->table("traketqua")->select("tendonvi, madonvi, noidung,datecreate,usercreate")->where("idklgb",$item->id)->find_all();
			//echo "<pre>"; print_r($arrklpb); exit();
			$vt=1;
			foreach($arkq as $kq) {				
				$kqth.= "\n".$vt."/ ".$kq->datecreate." _ ".$kq->usercreate.": ".$kq->noidung."\n";
				$vt++;
			} */
			// tra ket qua 
			$kqth = "";
			$arkq = $this->model->table("klphongban")->select("tendonvi, madonvi, traketqua as noidung,datecreate,usercreate")->where("idkl",$item->id)->where("traketqua <>"," ")->order_by('ngayhoanthanh','asc')->find_all();
			//echo "<pre>"; print_r($arrklpb); exit();
			$vt=1;
			foreach($arkq as $kq) {				
				$kqth.= "\n".$vt."/ ".$kq->datecreate." _ ".$kq->tendonvi.": ".$kq->noidung."\n";
				$vt++;
			}
			//end tra ket qua
			
			$ycpkh = "";			
			$arrycpkh = $this->model->table('ycpkh')->select('noidung')->where('idklgb',$item->id)->find_all();
			//echo "<pre>"; print_r($ycpkh); exit();
			$vt=1;
			if(count($arrycpkh)>0);
			foreach($arrycpkh as $yc) {
				$ycpkh.= $vt.": ".$yc->noidung."\n";
				$vt++;
			}
			
			$sheetIndex->setCellValueByColumnAndRow(0,$i,$i-1);
			$sheetIndex->setCellValueByColumnAndRow(1,$i,$codes." ");
			$sheetIndex->setCellValueByColumnAndRow(2,$i,$pbth);
			$sheetIndex->setCellValueByColumnAndRow(3,$i,(isset($item->madonvi)?strtoupper($item->madonvi).":":"").$noidung.$str_code);
			$sheetIndex->setCellValueByColumnAndRow(4,$i,$ngayhoanthanh);
			$sheetIndex->setCellValueByColumnAndRow(5,$i,$tinh_trang);
			$sheetIndex->getStyle("F".$i)->getFill()->getStartColor()->setRGB($mau);
			$objPHPExcel->getActiveSheet()->getStyle("B".$i)->getFill()->applyFromArray(array(
							'type' => PHPExcel_Style_Fill::FILL_SOLID,
							'startcolor' => array(
								 'rgb' => $mau
							)
						));
			$yckh = "";
			if(isset($getyeucaupkh[$item->id])){
				foreach($getyeucaupkh[$item->id] as $kk=>$vv2){
					$yckh.= "- ".$vv2.", \n";
				}
			}
			$sheetIndex->setCellValueByColumnAndRow(6,$i,$kqth);
			$sheetIndex->setCellValueByColumnAndRow(7,$i,$ycpkh);
			
			$diem=0;
			if($item->chamdiemdc!=0 )
				$diem = $item->chamdiemdc;
			else
				$diem = ($item->chamdiem!=0)?$item->chamdiem:0;
				
			$sheetIndex->setCellValueByColumnAndRow(8,$i,$diem);
			$sheetIndex->setCellValueByColumnAndRow(9,$i,$item->loaiketluan);
			$sheetIndex->setCellValueByColumnAndRow(10,$i,$item->sovanban);
			$sheetIndex->setCellValueByColumnAndRow(11,$i,$ngaygiaoban);
			$sheetIndex->setCellValueByColumnAndRow(12,$i,isset($list_nhanvien[$item->nguoiketluan])?$list_nhanvien[$item->nguoiketluan]:"");
			
			$sheetIndex->setCellValueByColumnAndRow(13,$i,$item->loaiketluan);
			$sheetIndex->setCellValueByColumnAndRow(14,$i,$item->ketluankhac);
			
			$sheetIndex->setCellValueByColumnAndRow(15,$i,$item->pheduyet);
			$tpduyet = "Chưa duyệt";
			if($item->tpduyet == 1){
				$tpduyet = "Đã duyệt";
			}
			$sheetIndex->setCellValueByColumnAndRow(16,$i,$tpduyet);
			$ghichu = strip_tags($item->ghichu);
			$ghichu = html_entity_decode($ghichu,ENT_QUOTES,"UTF-8");
			$ghichu = str_replace("&nbsp;","",$ghichu)."\n";
			$sheetIndex->setCellValueByColumnAndRow(17,$i,$ghichu);
			$i++;
		}

		$boderthin = "A3:T".($i-1);
        $sheetIndex->getStyle($boderthin)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
		#end
		$objPHPExcel->setActiveSheetIndex(0);
		$date = gmdate("dmYHis", time() + 7 * 3600);
		$endxls = '.xls';
        $this->excel_model->exportExcel($objPHPExcel, $versionExcel, "KLGB".$date.$endxls);
	}
	
	function runsql() {
		$id= $this->input->post('id');
		$obj = $this->model->table("tabs")->where("id",$id)->find();
		$result['status'] = "no";	
		$result['reason'] = "Không xác định";	
		if(!empty($obj->sql))
		{
			$res = $this->model->runsql($obj->sql);
			$result['status'] = "yes";
			$result['sql'] = $obj->sql;
			$result['content'] = $obj;
			$result['result'] = $res;
		} else 
			$result['reason'] = "SQL string is empty";
		echo json_encode($result);
	}
	
	function runlink() {
		$id= $this->input->post('id');
		$obj = $this->model->table("tabs")->where("id",$id)->find();
		$result['status'] = "no";	
		$result['reason'] = "Không xác định";		
		if(!empty($obj->links))
		{
			//print_r($obj); exit();
			$result['status'] = "yes";
			$result['link'] = $obj->links;
		} else 
			$result['reason'] = "Link string is empty";
		echo json_encode($result);
	}
	
	function linktest(){
		$data = new stdClass();		
		$content = $this->load->view('test', $data, true);
		$this->pub->write('content',$content,true);
        $this->pub->render();
	}
	function tinhTrangDetail(){
		 $this->load->helper('form');
		 $data = new stdClass();
		 $ids =  6;//$this->input->post('id');	
		 $login = $this->pub->GetSession('login');
		 $donvi = $login['donvi'];
		
//		 $query = $this->model->where('id',$ids)->find();	
		$query = $this->model->table("klphongban")->select("tendonvi, diemdieuchinh, ngayhoanthanh, types")->where("idkl",$ids)->find_all();
		 
		 $data = $query;
		 //print_r($data);
		// echo $this->load->view('tinhTrangDetail', $data, true);	
	}
}